package com.bulletelc.apollopre.utils;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.interfaces.enums.DrawableEnum;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * author: lhl
 * time  : 2017/10/19
 * desc  : 专属工具类
 */

public final class MyUtil {

    private MyUtil() {
        //empty
    }

    /**
     * 由于TextView及子类设置drawableTop、drawableBottom等时，不能在xml文件中对Drawable进行缩放。
     * 此工具类用于缩放drawable
     * @param de   设置drawable的位置，值为枚举类DrawableEnum（LEFT,TOP,RIGHT,BOTTOM）
     * @param tv   TextView及其子类
     * @param drawable  设置的图片，通过getResources().getDrawable(R.drawable.xxxx)获取
     * @param scale   缩放比例，1以内
     */
    public static void setDrawableLocation(DrawableEnum de, TextView tv, Drawable drawable, float scale) {
        setDrawableLocation(de,tv,drawable,0,0,scale,scale);
    }

    /**
     * 由于TextView及子类设置drawableTop、drawableBottom等时，不能在xml文件中对Drawable进行缩放。
     * 此工具类用于缩放drawable
     *
     * @param de 设置drawable的位置，值为枚举类DrawableEnum（LEFT,TOP,RIGHT,BOTTOM）
     * @param tv TextView及其子类
     * @param drawable 设置的图片，通过getResources().getDrawable(R.drawable.xxxx)获取
     * @param leftScale     缩放比例，1以内
     * @param topScale      缩放比例，1以内
     * @param rightScale    缩放比例，1以内
     * @param bottomScale   缩放比例，1以内
     */
    public static void setDrawableLocation(DrawableEnum de, TextView tv, Drawable drawable,
                                           float leftScale, float topScale, float rightScale, float bottomScale) {
        drawable.setBounds(
                (int) (drawable.getMinimumWidth() * leftScale),
                (int) (drawable.getMinimumHeight() * topScale),
                (int) (drawable.getMinimumWidth() * rightScale),
                (int) (drawable.getMinimumHeight() * bottomScale));

        switch (de) {
            case LEFT:
                tv.setCompoundDrawables(drawable,null,null,null);
                break;

            case TOP:
                tv.setCompoundDrawables(null,drawable,null,null);
                break;

            case RIGHT:
                tv.setCompoundDrawables(null,null,drawable,null);
                break;

            case BOTTOM:
                tv.setCompoundDrawables(null,null,null,drawable);
                break;
        }
    }

    /**
     * 计算年龄
     *
     * @param birthday 格式为：2000-07-28
     * @return
     */
    public static int getAge(String birthday) {
        int iage = 0;

        if (birthday != "" || birthday != null) {
            int year = Integer.parseInt(birthday.substring(0, 4));
            int month = Integer.parseInt(birthday.substring(5, 7));
            int day = Integer.parseInt(birthday.substring(8, 10));

            Calendar birthDate = new GregorianCalendar(year, month, day);
            Calendar today = Calendar.getInstance();

            if (today.get(Calendar.YEAR) > birthDate.get(Calendar.YEAR)) {
                iage = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR)
                        - 1;
                if (today.get(Calendar.MONTH) + 1 > birthDate
                        .get(Calendar.MONTH)) {
                    iage++;
                } else if (today.get(Calendar.MONTH) + 1 == birthDate
                        .get(Calendar.MONTH)) {
                    if (today.get(Calendar.DAY_OF_MONTH) > birthDate
                            .get(Calendar.DAY_OF_MONTH)) {
                        iage++;
                    }
                }
            }
            return iage;
        }
        return 0;
    }

    /**
     * 打开拨号界面
     *
     * @param context 上下文
     * @param phone  电话号码
     */
    public static void phoneDial(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phone));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    /**
     * 直接拨打电话(危险权限),需要运行时权限处理
     * <uses-permission android:name="android.permission.CALL_PHONE"/>
     *
     * @param context 上下文
     * @param phone  电话号码
     */
    @SuppressLint("MissingPermission")
    public static void phoneCall(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    /**
     * 复制文本到粘贴板
     *
     * @param context
     * @param text  复制的内容
     */
    public static void copyText(Context context, String text) {
        ClipboardManager cm= (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("text",text));
    }

    /**
     * 从剪贴板获取内容,粘贴
     * @param context
     */
    public static String pasteText(Context context) {
        ClipboardManager cm= (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (!cm.hasPrimaryClip()){
            return null;
        }
        ClipData cd=cm.getPrimaryClip();
        String text=cd.getItemAt(0).getText().toString();
        return text;
    }

    /**
     * 对包含中文的url进行编码
     *
     * @param url
     * @return
     */
    public static String urlEncode(String url) {
        String urlEncode=null;
        try {
            urlEncode = URLEncoder.encode(url, GlobalConfig.CODED_FORMAT);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlEncode;
    }

    /**
     * 对url进行解码
     * @param text
     * @return
     */
    public static String urlDecoder(String text) {
        String urlDecode=null;
        try {
            urlDecode = URLDecoder.decode(text, GlobalConfig.CODED_FORMAT);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlDecode;
    }

    /**
     * 获取post请求的header头token参数
     * @return
     */
    public static String getAuthToken(String token) {
        String authToken = NetWorkPath.AUTH_TOKEN_PRE + token;
        return authToken;
    }

    /**
     * 获取post请求的header头token参数
     * @return
     */
    public static String getAuthToken() {
        String authToken = NetWorkPath.AUTH_TOKEN_PRE + MyApplication.getToken();
        return authToken;
    }

    /**
     * 手机隐藏中间数字
     */
    public static String getConcealMobileNum(String num) {
        String cover = "*****";
        if (num != null) {
            StringBuilder sb = new StringBuilder(num);
            sb.replace(4,8,cover);
            return sb.toString();
        }
        return null;
    }

    /**
     * 微信分享的图片所需工具
     * @param bmp
     * @param needRecycle
     * @return
     */
    public static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 保留2位小数
     * @param value
     * @return
     */
    public static String format2(double value) {

        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(value);
    }

    /**
     * listView自适应高度
     * 解决viewPager添加listView高度问题
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        //((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除

        listView.setLayoutParams(params);
    }

    /**
     * 方法1设置tabitem下划线宽度
     * @param tabLayout
     */
    public static void reflex(final TabLayout tabLayout){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
                    int dp10 = DensityUtil.dip2px(tabLayout.getContext(), 10);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);
                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width ;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置ProgressBar显示/隐藏
     * @param b
     */
    public static void setProgressBar(View view, boolean b) {
        if (b) {
            view.setVisibility(View.VISIBLE);
            // 在上传中禁止交互
            //getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        } else {
            view.setVisibility(View.GONE);
            // 恢复Activity交互
            //getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    /***
     * 获取url 指定name的value;
     * @param url
     * @param name
     * @return
     */
    public static String getUrlValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

}
